<?php
require_once('Mysqldump.php');
require_once('class-qiniu.php');
use Ifsnop\Mysqldump as IMysqldump;

//添加定时任务周期
function backup_qiniu_add_schedules($schedules) {
	$schedules['weekly'] = array(
		'interval' => 604800,
		'display' => '每周一次',
	);
	$schedules['monthly'] = array(
		'interval' => 2592000,
		'display' => '每月一次',
	);
	return $schedules;
}
add_filter('cron_schedules', 'backup_qiniu_add_schedules', 10, 1);
//删除任务
function backup_qiniu_delete_cron() {
	if(wp_next_scheduled('backup_qiniu')) {
		wp_clear_scheduled_hook('backup_qiniu');
	}
}
register_deactivation_hook(__FILE__, 'backup_qiniu_delete_cron');
register_uninstall_hook(__FILE__, 'backup_qiniu_delete_cron');
//任务挂接
function backup_qiniu_cron_fun() {
	backup_qiniu_cron();
}
add_action('backup_qiniu', 'backup_qiniu_cron_fun');
//定时备份
function backup_qiniu_cron() {
	$error = backup_qiniu_mysql();
	if($error) {
		backup_qiniu_mail($error);
	}
}
//发送邮件
function backup_qiniu_mail($msg='') {
	$blogname = get_bloginfo('name');
	$adminemail = get_bloginfo('admin_email');
	$title = $blogname . ' - 备份通知';
	$headers = array('Content-Type: text/html; charset=UTF-8');
	wp_mail($blogname . ' <' . $adminemail . '>', $title, $msg, $headers);
}
//备份数据库
function backup_qiniu_mysql() {
	if(function_exists('set_time_limit')) {
		set_time_limit(0);
	}
	$suffix = wp_date('j');

	$error = '';
	$temp = tempnam(sys_get_temp_dir(), 'qiniu_');
	try {
		$dump = new IMysqldump\Mysqldump('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
		$dump->start($temp);
	} catch (\Exception $e) {
		$error = $e->getMessage();
	}
	if(!$error) {
		//打包文件
		$size = filesize($temp);
		$handle = fopen($temp, 'rb');
		$sql = fread($handle, $size);
		fclose($handle);
		unlink($temp);

		$file = tempnam(sys_get_temp_dir(), 'qiniu_') . '.zip';
		$zip = new ZipArchive;
		if($zip->open($file, ZIPARCHIVE::CREATE ) === TRUE) {
			$zip->addFromString(DB_NAME . '.sql', $sql);
			$zip->close();
		}

		//上传到七牛
		$domain = parse_url(get_option('siteurl'));
		$domain = $domain['host'];
		$save = $domain . '/database/' . DB_NAME . '_' . $suffix . '.zip';

		$Qiniu = new Qiniu();
		$error = $Qiniu->auth();
		if(!$error) {
			$Qiniu->token($save);
			$error = $Qiniu->upload($save, $file);
		} 
		unlink($file);
	}
	return $error;
}
//获取原图和缩略图路径
function backup_qiniu_images($meta) {
	if(!$meta || empty($meta['file'])) return;
	$basepath = dirname($meta['file']) . '/';
	$images[] = $meta['file'];
	if(!empty($meta['sizes'])) {
		foreach($meta['sizes'] as $size) {
			if(!$size['file']) continue;
			$images[] = $basepath . $size['file'];
		}
	}
	$images = array_unique($images);
	return $images;
}
//上传图片
function backup_qiniu_upload_images($meta, $attachment_id) {
	if(!wp_attachment_is_image($attachment_id)) return $meta;

	$Qiniu = new Qiniu();
	$error = $Qiniu->auth();
	if($error) {
		$error = "初始化凭证失败：$error";
	} else {
		$domain = parse_url(get_option('siteurl'));
		$domain = $domain['host'];
		$upload_path = get_option('upload_path');
		$upload_path = $upload_path ? trim($upload_path, '/') : 'wp-content/uploads';
		$upload_path = ABSPATH . $upload_path . '/'; 

		$images = backup_qiniu_images($meta);
		foreach($images as $image) {
			$save = $domain . '/uploads/' . $image;
			$Qiniu->token($save);
			$upload = $Qiniu->upload($save, $upload_path . $image);
			if($upload) $error .= $upload . ' - ' . $image . '<br>';
		}
	}
	if($error) {
		$error = "图片 $attachment_id 的上传错误报告：<br><br>$error";
		backup_qiniu_mail($error);
	}
	return $meta;
}
add_filter('wp_generate_attachment_metadata', 'backup_qiniu_upload_images', 10, 2);
//上传文件
function backup_qiniu_upload_file($attachment_id) {
	if(wp_attachment_is_image($attachment_id)) return;

	$Qiniu = new Qiniu();
	$error = $Qiniu->auth();
	if($error) {
		$error = "初始化凭证失败：$error";
	} else {
		$domain = parse_url(get_option('siteurl'));
		$domain = $domain['host'];
		$upload_path = get_option('upload_path');
		$upload_path = $upload_path ? trim($upload_path, '/') : 'wp-content/uploads';
		$upload_path = ABSPATH . $upload_path . '/'; 

		$file = get_attached_file($attachment_id);
		$path = str_replace($upload_path, '', $file);
		$save = $domain . '/uploads/' . $path;

		$Qiniu->token($save);
		$error = $Qiniu->upload($save, $file);
	}
	if($error) {
		$error = "文件 $attachment_id 的上传错误报告：<br><br> $error";
		backup_qiniu_mail($error);
	}
}
add_action('add_attachment', 'backup_qiniu_upload_file', 10, 1);
//同步删除
function backup_qiniu_delete_attachment($attachment_id) {
	$domain = parse_url(get_option('siteurl'));
	$domain = $domain['host'];
	$upload_path = get_option('upload_path');
	$upload_path = $upload_path ? trim($upload_path, '/') : 'wp-content/uploads';
	$upload_path = ABSPATH . $upload_path . '/'; 

	$Qiniu = new Qiniu();
	$error = $Qiniu->auth();
	if($error) {
		$error = "初始化凭证失败：$error";
	} else {
		if(wp_attachment_is_image($attachment_id)) {
			$meta = wp_get_attachment_metadata($attachment_id);
			$backup_sizes = get_post_meta($attachment_id, '_wp_attachment_backup_sizes', true);
			if($backup_sizes) {
				$meta['sizes'] = wp_parse_args($meta['sizes'], $backup_sizes);
			}
			$images = backup_qiniu_images($meta);
			$images = array_unique($images);
			$delimages = array();
			foreach($images as $image) {
				if(!$image) continue;
				$delimages[] = $domain . '/uploads/' . $image;
			}
			$error = $Qiniu->batchDelete($delimages);
		} else {
			$file = get_attached_file($attachment_id);
			$path = str_replace($upload_path, '', $file);
			if($path) {
				$delfile = $domain . '/uploads/' . $path;
				$error = $Qiniu->delete($delfile);
			}
		}
	}
	if($error) {
		$error = "文件 $attachment_id 的删除错误报告：<br><br> $error";
		backup_qiniu_mail($error);
	}
}
add_action('delete_attachment', 'backup_qiniu_delete_attachment', 10, 1);

//获取所有图片ID
function backup_qiniu_get_attachment_ids() {
	global $wpdb;
	$ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type='attachment'");
	return $ids;
}
?>